package com.zbkj.service.service.order.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.zbkj.dal.base.enums.*;
import com.zbkj.dal.base.enums.merchant.MerOrderApptType;
import com.zbkj.dal.common.utils.DateConverter;
import com.zbkj.dal.dao.OrderDao;
import com.zbkj.dal.dao.ShareMapper;
import com.zbkj.dal.entity.ba.BizImg;
import com.zbkj.dal.entity.ba.Share;
import com.zbkj.dal.entity.merchant.Merchant;
import com.zbkj.dal.entity.merchant.MerchantOrderAppointment;
import com.zbkj.dal.entity.order.Order;
import com.zbkj.dal.entity.product.ProductBrand;
import com.zbkj.dal.pojo.request.PageParamRequest;
import com.zbkj.dal.pojo.request.order.platform.PlatformShareOrderQueryRequest;
import com.zbkj.dal.pojo.response.ba.ShareDetailResponse;
import com.zbkj.dal.pojo.response.ba.ShareResponse;
import com.zbkj.dal.pojo.response.order.platform.PlatformShareOrderResponse;
import com.zbkj.service.service.BizImgService;
import com.zbkj.service.service.MerchantService;
import com.zbkj.service.service.OrderInvoiceService;
import com.zbkj.service.service.ProductBrandService;
import com.zbkj.service.service.merchant.MerchantOrderAppointmentService;
import com.zbkj.service.service.order.platform.AdminPlatformShareOrderV2Service;
import com.zbkj.service.util.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author wangzhengyan
 * @date 2024/4/12 9:37 PM
 */
@Service
@Slf4j
public class AdminPlatformShareOrderV2ServiceImpl extends ServiceImpl<ShareMapper, Share> implements AdminPlatformShareOrderV2Service {

    @Resource
    private BizImgService bizImgService;
    @Resource
    private ProductBrandService productBrandService;
    @Resource
    private MerchantService merchantService;
    @Resource
    private OrderInvoiceService orderInvoiceService;
    @Resource
    private MerchantOrderAppointmentService merchantOrderAppointmentService;

    @Override
    public PageInfo<PlatformShareOrderResponse> querySharesPaged(PlatformShareOrderQueryRequest shareQueryRequest, PageParamRequest pageParamRequest) {
        LambdaQueryWrapper<Share> queryWrapper = Wrappers.lambdaQuery(Share.class);
        if (StringUtils.isNotEmpty(shareQueryRequest.getOrderNo())) {
            queryWrapper.eq(Share::getOrderNo, shareQueryRequest.getOrderNo());
        }
        if (shareQueryRequest.getStatus() != null) {
            queryWrapper.in(Share::getStatus, shareQueryRequest.getStatus());
        }
        if (StringUtils.isNotEmpty(shareQueryRequest.getCategory())) {
            queryWrapper.like(Share::getProductTypeFinal, "%" + shareQueryRequest.getCategory() + "%");
        }
        if (StringUtils.isNotEmpty(shareQueryRequest.getBrand())) {
            queryWrapper.like(Share::getBrandFinal, "%" + shareQueryRequest.getBrand() + "%");
        }
        queryWrapper.orderByDesc(Share::getId);
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<Share> list = this.list(queryWrapper);
        PageInfo<Share> pageInfo = PageInfo.of(list);

        PageInfo<PlatformShareOrderResponse> result = new PageInfo<>();
        result.setTotal(pageInfo.getTotal());
        List<PlatformShareOrderResponse> dtos = Lists.newArrayList();
        for (Share share : pageInfo.getList()) {
            PlatformShareOrderResponse shareResponse = new PlatformShareOrderResponse();
            BeanUtils.copyProperties(share, shareResponse);
            shareResponse.setShareModeName(BizShareModeEnum.toName(share.getShareMode()));
            shareResponse.setStatusDesc(BizSharedOrderStatus.text(share.getStatus()));
            dtos.add(shareResponse);
        }
        result.setList(dtos);
        UserUtils.fillUsers(dtos);
//        if (CollectionUtils.isNotEmpty(dtos)) {
//            List<Integer> operatorIds = dtos.stream().filter(p -> p.getOperatorId() != null).map(m -> m.getOperatorId()).distinct().collect(Collectors.toList());
//            if (CollectionUtils.isNotEmpty(operatorIds)) {
//                Map<Integer, String> nameMapByIdList = adminService.getNameMapByIdList(operatorIds);
//                for (ShareResponse dto : dtos) {
//                    if (dto.getOperatorId() != null) {
//                        dto.setOperatorName(nameMapByIdList.get(dto.getOperatorId()));
//                    }
//                }
//            }
//        }
        return result;
    }

    @Override
    public ShareDetailResponse detail(String orderNo) {
        LambdaQueryWrapper<Share> lqw = Wrappers.lambdaQuery();
        lqw.eq(Share::getOrderNo, orderNo);
        Share share = this.getOne(lqw);
        if (Objects.isNull(share)) {
            return null;
        }
        // 获取图片并且进行排序
        Map<RecyclePositionEnums, BizImg> bizImgs = bizImgService.listByBizId(BizTypeEnum.SHARE.getType(), share.getId()).stream()
                .collect(Collectors.toMap(img -> RecyclePositionEnums.valueOf(img.getPosition()), Function.identity()));
        // -------------------------------------- 构建Tips字段 --------------------------------------
//        String tips = getShareTipsForFrontApi(orderNo, share);
        ShareDetailResponse shareDetailResponse = ShareDetailResponse.buildByShare(share, bizImgs, "");
        // 设置用户提交品牌信息
        String brand = share.getBrand();
        ProductBrand brand1 = productBrandService.getById(brand);
        shareDetailResponse.getUserSubmit().setBrand(brand1.getName());
        // 设置初评提交的品牌信息
        String brandFinal = share.getBrandFinal();
        if (StringUtils.isNotEmpty(brandFinal)) {
            if (StringUtils.equals(brand, brandFinal)) {
                shareDetailResponse.getInitialEvaluation().setBrand(brand1.getName());
                shareDetailResponse.setProductName(brand1.getName() + ProductTypeEnums.valueOf(share.getProductType()).getDesc());
            } else {
                ProductBrand brand2 = productBrandService.getById(brandFinal);
                shareDetailResponse.getInitialEvaluation().setBrand(brand2.getName());
                shareDetailResponse.setProductName(brand2.getName() + ProductTypeEnums.valueOf(share.getProductType()).getDesc());
            }
        }

        // 获取总店的商户地址
        Merchant merchant = merchantService.getShareServiceMerchant();

        // ----------------------------------------- 设置预约上门信息 -----------------------------------------
        if (Objects.equals(BizSharedOrderStatus.PENDING_VALUATION.name(), share.getStatus())
                && Objects.equals(BizSharedOrderStatus.SubStatus.WAITING_USER_PICKUP.name(), share.getSubStatus())) {
            MerchantOrderAppointment appointment = merchantOrderAppointmentService.findAppointmentByOrderId(share.getOrderNo(), MerOrderApptType.SHARED_CREATE);
            ShareDetailResponse.InStoreAppt inStoreAppt = new ShareDetailResponse.InStoreAppt();
            inStoreAppt.setReservationNo(appointment.getApptCode());
            inStoreAppt.setName(merchant.getName());
            inStoreAppt.setPhone(merchant.getPhone());
            inStoreAppt.setAddress(merchant.getProvince() + merchant.getCity() + merchant.getDistrict() + merchant.getAddressDetail());
            inStoreAppt.setLatitude(merchant.getLatitude());
            inStoreAppt.setLongitude(merchant.getLongitude());
            inStoreAppt.setDateDesc(DateConverter.convertDate(appointment.getApptDate()));
            inStoreAppt.setStartTime(appointment.getApptTimeStart());
            inStoreAppt.setEndTime(appointment.getApptTimeEnd());
            shareDetailResponse.setInStoreAppt(inStoreAppt);
        }

        // ----------------------------------------- 设置物流轨迹信息 -----------------------------------------
        shareDetailResponse.setOrderLogisticsResponse(orderInvoiceService.findTraceByOrderNoAndLastTraceOnly(orderNo));


        return shareDetailResponse;
    }
}
